'use strict';

const qs = require("querystring") 

// 获取字符的默认值
const sql_str_default = (new_paramsStr,paramsStr='')=>{
    return new_paramsStr ? `${new_paramsStr}` : paramsStr 
}

// 获取where语句
const sql_where = (new_paramsObj)=>{
    if(new_paramsObj == null) return '';
    // where参数中的参数值需要使用引号包含， 使用and连接
    let t_paramsObj = {}
    Object.keys(new_paramsObj).map(item=>{ 
        t_paramsObj[item] = `'${new_paramsObj[item]}'`
    })
   return  t_paramsObj ? ` where ${qs.stringify(t_paramsObj).replace(/&/gi, ' and ')}`  : ''
}
 
// 获取select语句
const sql_select = (table,fillable,hidden,new_field=null,strict=true)=>{
    if(strict){
        return new_field ? `select ${new_field} from ${table}` : `select ${fillable} from ${table}` 
    }else{ 
        return new_field ? `select ${new_field} from ${table}` : `select ${[...fillable,...hidden]} from ${table}` 
    }
}
 
// 获取update语句
const sql_update = (table,new_paramsObj)=>{  
    // set参数中的参数值需要使用引号包含,并且需要使用“,”逗号连接
    let t_paramsObj = {}
    Object.keys(new_paramsObj).map(item=>{
        if(item.endsWith('Time') || item.endsWith('_time')){
            // 日期类型的，不添加引号
            t_paramsObj[item] = `${new_paramsObj[item]}`;
        }else{ 
            t_paramsObj[item] = `'${new_paramsObj[item]}'`
        }
    })
    return `update ${table} set  ${qs.stringify(t_paramsObj).replace(/&/gi, ' , ')}` 
}
 
// 获取insert语句 
const sql_insert = (table,new_fieldObj,strict=true,primaryKey='id') =>{ 
    let keys = Object.keys(new_fieldObj);
    let values = Object.values(new_fieldObj);
    keys.unshift(primaryKey);
    values.unshift(null);
    // set参数中的参数值需要使用引号包含,并且需要使用“,”逗号连接
    let t_values = values.map((item,index)=>{ 
        if(index == 0){
            return 'NULL';
        }else{  
            // 插入数据的日期格式就是字符串
            return `'${item}'` 
        }
    }) 
    if(strict){
        return  `insert into ${table}(${keys}) values(${t_values})`; 
    }else{ 
        return  `insert into ${table} values(${t_values})`; 
    }
}
 
// 获取delete语句
const sql_delete = (table,strict=true)=>{   
    if(strict){ 
        return `delete from ${table} ` 
    }else{ 
        return `truncate from ${table} ` 
    }
}
  

module.exports = {
    sql_str_default,
    sql_where,
    sql_select,
    sql_update,
    sql_insert,
    sql_delete, 
}

